package zhtt.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;

/**
 *
 compile group: 'opensymphony', name: 'quartz-all', version: '1.6.1'
 */
public class ApplicationInitializeListener implements  ServletContextListener {

    private final Logger logger = LoggerFactory.getLogger(ApplicationInitializeListener.class);

//    @Override
    public void contextInitialized(ServletContextEvent event) {
        System.out.println("应用系统 初始化...");
        WebApplicationContext applicationContext = getApplicationContext(event);
        try {
            initialize(applicationContext);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//    @Override
    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("应用系统结束");
        WebApplicationContext applicationContext = getApplicationContext(event);
        try {
            destroy(applicationContext);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private WebApplicationContext getApplicationContext(ServletContextEvent event) {
        ServletContext servletContext = event.getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        return applicationContext;
    }

    private void initialize(WebApplicationContext applicationContext) throws Exception {
        ServletContext context = applicationContext.getServletContext();
        InitService initService =(InitService) applicationContext.getBean("initService");
        initService.sync();
    }

    private void destroy(WebApplicationContext applicationContext) throws Exception {
        ServletContext context = applicationContext.getServletContext();
        InitService initService =(InitService) applicationContext.getBean("initService");
        initService.destroy();
    }
}
